import cv2
import os
from matplotlib import pyplot as plt

method = cv2.TM_SQDIFF_NORMED

# Read the images from the file
small_image = cv2.imread('d:/test/x.png')
large_image = cv2.imread('d:/test/2.tif')

h = small_image.shape[0]
w = small_image.shape[1]
result = cv2.matchTemplate(small_image, large_image, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
top_left = min_loc
bottom_right = (top_left[0] + w, top_left[1] + h)

cv2.rectangle(large_image, top_left, bottom_right, 255, 2)
#large_image.crop((top_left[0]:w, top_left[1]:h, ))
cv2.imwrite('d:\\adf.png', large_image[top_left[1]:h+top_left[1], top_left[0]:w+top_left[0]])
# plt.subplot(221), plt.imshow(small_image,cmap= "gray")
# plt.title('Original Image'), plt.xticks([]),plt.yticks([])
# plt.subplot(222), plt.imshow(large_image,cmap= "gray")
# plt.title('template Image'),plt.xticks([]),plt.yticks([])
# plt.show()
src=''      ##directory contains the book image file
data_path=''    ##directory contains the old  question and answer images
out_path=''        # directory for output

book_imgs=os.listdir(src)
i=0
for img in os.listdir(data_path):
    small_img=cv2.imread(img)
    while i< len(book_imgs):
        cv2.imread(book_imgs[i])